# coding=utf-8

import unittest
from datetime import datetime
import traceback

from src.report import HTMLTestRunner
from src.config import Config
from src.report import sendEmail
from src.runthroughcase import addTestCaseByExcel
from src.log import Log

logger = Log().getLogger # 创建日志记录对象 logger

# 构造测试集
try:
    logger.info("构建测试用例开始")
    suite = unittest.TestSuite()
    # 按照Excel案例配置运行
    addTestCaseByExcel(suite)
    logger.info("构建测试用例结束")
except:
    logger.error("测试用例构建失败。报错信息:\n" + traceback.format_exc())

# 执行测试集
if __name__ == '__main__':
    time = datetime.now().strftime("%Y%m%d_%H%M%S")
    filepath = Config.projectDir + r"\report\ResultReport_%s.html" % time

    # 不生成测试报告运行
    # runner = unittest.TextTestRunner()
    # runner.run(suite)
    # 生成测试报告运行
    try:
        logger.info("测试执行开始")
        with open(filepath, 'wb') as fp:
            # 调用HTMLtestrunner来执行脚本并生成测试报告，html格式的
            runner = HTMLTestRunner(stream=fp, title='report', description='demo')
            runner.run(suite)
        logger.info("测试执行结束")
    except:
        logger.error("测试执行失败。报错信息:\n" + traceback.format_exc())
    # 邮件发送
    try:
        logger.info("邮件发送开始")
        sendEmail(filepath) # 发送邮件
        logger.info("邮件发送结束")
    except:
        logger.error("邮件发送失败。报错信息:\n" + traceback.format_exc())
